<template>
  <Dialog v-model="dialogVisible" title="Logo" class="logo-dialog">
    <el-radio-group v-model="logoRadio">
      <el-radio :value="1">默认</el-radio>
      <el-radio :value="2">自定义</el-radio>
    </el-radio-group>
    <el-upload class="avatar-uploader" v-model:file-list="fileList" :action="importUrl" :headers="uploadHeaders"
      :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
      v-show="logoRadio == 2">
      <img v-if="imageUrl" :src="imageUrl" class="avatar" />
      <el-icon v-else class="avatar-uploader-icon">
        <Plus />
      </el-icon>
      <template #tip>
        <div class="el-upload__tip">
          提示：仅允许上传 jpg/png 格式文件，小于5MB
        </div>
      </template>
    </el-upload>
    <div v-show="logoRadio == 1">
      <img v-for="(image, index) in images" :key="index" :src="image" alt="" srcset="" width="100"
        @click="selectImage(image)" :class="selectImg && image.indexOf(selectImg) != -1 ? 'selected' : ''" />
    </div>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { Plus } from '@element-plus/icons-vue'
import earth from '@/assets/imgs/earth.png'
import growth from '@/assets/imgs/growth.png'
import satellite from '@/assets/imgs/satellite.png'
import spaceMission from '@/assets/imgs/space-mission.png'
import { getAccessToken, getTenantId } from '@/utils/auth'
const dialogVisible = ref(false)
const logoRadio = ref(1)
const formLoading = ref(false) // 表单的加载中:1）修改时的数据加载；2）提交的按钮禁用
const message = useMessage() // 消息弹窗
const images = ref([earth, growth, satellite, spaceMission])
const selectImg = ref('')
const importUrl =
  import.meta.env.VITE_BASE_URL + import.meta.env.VITE_API_URL + '/api-publish/upload'
const uploadHeaders = ref({
  Authorization: 'Bearer ' + getAccessToken(),
  'tenant-id': getTenantId()
})
const fileList = ref()
const logo = ref()
/** 打开弹窗 */
const open = async (row?: any) => {
  dialogVisible.value = true
  resetForm()
}
const resetForm = () => {
  fileList.value = []
  imageUrl.value = ''
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
const imageUrl = ref('') // 上传图片预览地址
const selectImage = (imageUrl) => {
  selectImg.value = imageUrl.split('/').pop()
  fetch(imageUrl)
    .then(response => response.blob())
    .then(async (blob) => {
      const file = new File([blob], imageUrl.split('/').pop(), { type: blob.type });
      Object.assign(file, {
        uid: Date.now(),
        url: imageUrl,
        raw: blob
      });
      const formData = new FormData();
      formData.append('file', file);
      const uploadResponse = await fetch(importUrl, {
        method: 'POST',
        headers: uploadHeaders.value,
        body: formData,
      });
      if (uploadResponse.ok) {
        const result = await uploadResponse.json();
        logo.value = result.data
      }
    })
    .catch(error => {
      console.log(error)
    });
}
const handleAvatarSuccess = async (
  response,
  uploadFile
) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  logo.value = response.data
}

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
    message.error('图片格式不正确!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 5) {
    message.error('图片大小不得大于 5MB!')
    return false
  }
  return true
}

const emit = defineEmits(['success'])

/** 提交表单 */
const submitForm = async () => {
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success', logo.value)
}
</script>

<style lang="scss">
.logo-dialog {

  .avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
    margin-top: 10px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
  }

  .el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
  }

  .selected {
    border: 2px solid #2d81f6;
  }

  img {
    margin: 0 10px;
    border: 2px solid transparent;
    cursor: pointer;
  }
}

.el-upload {
  img {
    width: 100%;
  }
}
</style>
